import { Injectable } from '@nestjs/common';
import { CollectModel } from 'src/Scheam/collect.scheam';
import { FoodModel } from 'src/Scheam/food.scheam';
type Data = {
  user_id: string,
  food_id: string
}
@Injectable()
export class CollectService {
  async creact(data: Data) {

    try {
      return await CollectModel.create({ ...data, collect_time: Date.now() });

    } catch (error) {
      return false
    }
  }
  async delectOne(body: Data) {
    try {
      return await CollectModel.deleteOne({
        user_id: body.user_id,
        food_id: body.food_id
      })
    } catch (error) {
      return false
    }

  }
  async getOne(data: Data) {
    try {
      return await CollectModel.findOne({
        user_id: data.user_id,
        food_id: data.food_id
      })
    } catch (error) {
      return false
    }
  }

  //.skip(skip).limit(6).sort({ "publish_time": "desc" }).select('-__v -type -rich_text -catalog -publish_time')
  async getList(user_id, skip = 0) {
    console.log(Number(skip))
    return await CollectModel.aggregate([
      {
        $match: { user_id: user_id }
      },
      {
        $addFields: {
          food_id: { $toObjectId: "$food_id" }
        }
      },
      {
        $lookup: {
          from: "food",
          localField: "food_id",
          foreignField: "_id",
          as: "foods"
        }
      },
      {
        $unwind: "$foods"
      },
      {
        $skip: Number(skip)
      },
      {
        $sort: { 'collect_time': -1 }
      },
      {
        $limit: 6
      },

      {
        //最后返回前需要保留的字段，1保存，
        $project: {
          "foods._id": 1,
          "foods.title": 1,
          "foods.user_id": 1,
          "foods.Cover_img": 1,
          "foods.rich_text": 1,
          "foods.texttual": 1,
          "foods.publish_time": 1,
          "foods.review": 1
        }
      }

    ])

  }

  async useCollect(id: string) {
    return {
      collect: await CollectModel.aggregate([
        {
          $match: { user_id: id }
        },
        {
          $count: "collect"
        }
      ]),
      food: await FoodModel.aggregate([
        {
          $match: { user_id: id }
        },
        {
          $count: "food"
        }
      ])
    }

  }
}
